import { _decorator, Component, Node, tween, Vec3, EventTouch, systemEvent, SystemEvent, Tween, EventMouse, error, SpriteFrame, Sprite, Color, find, Animation } from 'cc';
import { GLOBALUtil } from './GlobalUtil';
import { IDManager } from './IDManager';
import { GLOBALVar } from './GlobalVar';
const { ccclass, property } = _decorator;

@ccclass('PersonalPageManager')
export class PersonalPageManager extends Component {
    @property({ type: [Node], tooltip: "CardFrame" })
    cardFrames: Node[] = [];
    @property({ type: Node, tooltip: "Layout"})
    layout: Node = null;
    @property({ type: Node, tooltip: "BtnChooseCardFrame"})
    BtnChooseCardFrame: Node = null;

    // 椭圆长半轴
    @property
    radiusX: number = 140;
    // 椭圆短半轴
    @property
    radiusY: number = 86;

    @property
    period: number = 15;

    // 最小缩放比例
    @property
    minScale: number = 0.5;
    // 最大缩放比例
    @property
    maxScale: number = 1.5;

    // 控制触摸交互功能是否启用
    @property
    enableTouchInteraction: boolean = true;

    private isAnimationPaused: boolean = false;
    private touchStartX: number = 0;
    private currentAngles: number[] = [];
    private tweens: Tween<Node>[] = [];

    start() {
        this.initCardPositions();
        this.startCardMotion();

        if (this.enableTouchInteraction) {
            this.layout.on(SystemEvent.EventType.TOUCH_START, this.onTouchStart, this);
            this.layout.on(SystemEvent.EventType.TOUCH_MOVE, this.onTouchMove, this);
            this.layout.on(SystemEvent.EventType.TOUCH_END, this.onTouchEnd, this);
            this.layout.on(SystemEvent.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
        }

        // 为按钮添加点击事件监听器
        // this.BtnChooseCardFrame.on(Node.EventType.TOUCH_END, this.onButtonClick, this);
    }

    protected onEnable(): void {
        //播放动画
        this.node.getChildByName("PersonalPanel").getComponent(Animation).play();
        //获取数据库中的CardFrame数据更新CardFrame的显示
        GLOBALUtil.getCardFrame()
        .then((data: JSON) => {
            for (const key in data) {
                if (Object.prototype.hasOwnProperty.call(data, key)) {
                    const element = data[key];
                    this.cardFrames.forEach((card, index) => {
                        let name = "";
                        if (index <= 9) {
                            name = `CardFrame_100${index}`;
                        } else {
                            name = `CardFrame_10${index}`;
                        }
                        // 根据 key 匹配 CardFrame
                        if (name.includes(key) && element == 1) {
                            const childNode = card.getChildByName(name);
                            if (childNode) {
                                const sprite = childNode.getComponent(Sprite);
                                if (sprite) {
                                    sprite.color = new Color(255, 255, 255, 255);
                                }
                            }
                        }
                    });
                }
            }
        }).catch(error => {
            console.error(error);
        })
    }

    update(deltaTime: number) {

    }

    initCardPositions() {
        const cardCount = this.cardFrames.length;
        for (let i = 0; i < cardCount; i++) {
            const angle = (2 * Math.PI * i) / cardCount;
            this.currentAngles[i] = angle;
            // 使用椭圆参数方程计算位置
            const x = this.radiusX * Math.cos(angle);
            // 给 y 坐标加上 80 实现上移
            const y = this.radiusY * Math.sin(angle) + 80;
            this.cardFrames[i].setPosition(new Vec3(x, y, 0));
            // 根据角度调整初始缩放
            const scaleFactor = this.adjustcardFramescale(this.cardFrames[i], angle);
            // 根据缩放比例设置初始 zIndex
            this.setCardZIndex(this.cardFrames[i], scaleFactor);
        }
    }

    startCardMotion() {
        const cardCount = this.cardFrames.length;
        for (let i = 0; i < cardCount; i++) {
            const card = this.cardFrames[i];
            const startAngle = this.currentAngles[i];
            const t = tween(card)
              .repeatForever(
                    tween()
                      .by(this.period, { position: new Vec3(0, 0, 0) }, {
                            onUpdate: (target, ratio) => {
                                if (this.isAnimationPaused) return;
                                // 修改角度计算方式，实现顺时针旋转
                                const currentAngle = startAngle - 2 * Math.PI * ratio;
                                this.currentAngles[i] = currentAngle;
                                // 使用椭圆参数方程计算位置
                                const x = this.radiusX * Math.cos(currentAngle);
                                // 给 y 坐标加上 80 实现上移
                                const y = this.radiusY * Math.sin(currentAngle) + 80;
                                target.setPosition(new Vec3(x, y, 0));
                                // 根据当前角度调整缩放
                                const scaleFactor = this.adjustcardFramescale(target, currentAngle);
                                // 根据缩放比例更新 zIndex
                                this.setCardZIndex(target, scaleFactor);
                            }
                        })
                )
              .start();
            this.tweens[i] = t;
        }
    }

    // 根据卡牌的角度调整缩放比例
    adjustcardFramescale(card: Node, angle: number) {
        // 将角度转换到 [0, 2π] 范围
        angle = angle % (2 * Math.PI);
        if (angle < 0) {
            angle += 2 * Math.PI;
        }
        // 调整角度偏移，让最下方角度为 0
        angle = (angle + Math.PI / 2) % (2 * Math.PI);
        // 根据角度计算缩放比例，使用余弦函数来实现平滑过渡
        let scaleFactor = (Math.cos(angle) + 1) / 2;
        scaleFactor = this.minScale + scaleFactor * (this.maxScale - this.minScale);
        card.setScale(new Vec3(scaleFactor, scaleFactor, 1));
        return scaleFactor;
    }

    // 根据缩放比例设置卡牌的 zIndex
    setCardZIndex(card: Node, scaleFactor: number) {
        // 这里简单地将缩放比例映射到 zIndex 范围
        const minZIndex = 0;
        const maxZIndex = 100;
        // 正确映射，大缩放比例对应大 zIndex
        const zIndex = Math.floor(minZIndex + (scaleFactor - this.minScale) / (this.maxScale - this.minScale) * (maxZIndex - minZIndex));
        card.setSiblingIndex(zIndex);
    }

    private onTouchStart(event: EventTouch) {
        this.isAnimationPaused = true;
        this.touchStartX = event.getLocationX();
        for (let t of this.tweens) {
            t.stop();
        }
    }

    private onTouchMove(event: EventTouch) {
        const currentX = event.getLocationX();
        const deltaX = currentX - this.touchStartX;
        const angleDelta = deltaX * 0.01; // 调整这个系数来控制旋转速度

        const cardCount = this.cardFrames.length;
        for (let i = 0; i < cardCount; i++) {
            const card = this.cardFrames[i];
            this.currentAngles[i] += angleDelta;
            const currentAngle = this.currentAngles[i];
            // 使用椭圆参数方程计算位置
            const x = this.radiusX * Math.cos(currentAngle);
            // 给 y 坐标加上 80 实现上移
            const y = this.radiusY * Math.sin(currentAngle) + 80;
            card.setPosition(new Vec3(x, y, 0));
            // 根据当前角度调整缩放
            const scaleFactor = this.adjustcardFramescale(card, currentAngle);
            // 根据缩放比例更新 zIndex
            this.setCardZIndex(card, scaleFactor);
        }

        this.touchStartX = currentX;
    }

    private onTouchEnd() {
        this.isAnimationPaused = false;
        this.startCardMotion();
    }

    // 找出 Y 轴最小的卡牌
    private findCardWithMinY() {
        let minY = Infinity;
        let cardWithMinY: Node | null = null;

        for (const card of this.cardFrames) {
            const position = card.getPosition();
            if (position.y < minY) {
                minY = position.y;
                cardWithMinY = card;
            }
        }

        return cardWithMinY;
    }

    // 按钮点击事件处理函数
    private onButtonClick() {
        const card = this.findCardWithMinY();
        if (card) {
            // 请求使用CardFrame
            const cardFrameId = card.getComponent(IDManager).getID();
            GLOBALUtil.setCardFrame(cardFrameId)
            .then((response) => {
                if(response.code == 0) {
                    GLOBALUtil.LoadMessage(true, response.msg, this.node, new Vec3(50, 950, 0), true, 2);
                } else if (response.code == 1) {
                    //把当前皮肤赋值给全局变量
                    GLOBALVar.CardFrameUsed = cardFrameId;
                    GLOBALUtil.LoadMessage(true, response.msg, this.node, new Vec3(50, 950, 0), true, 1);
                }
            })
        } else {
            console.log('没有找到卡牌');
        }
    }

    onClickClose() {
        this.node.active = false;
    }
}